package com.renwei.yunlong.activity.work;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.google.gson.Gson;
import com.renwei.yunlong.R;
import com.renwei.yunlong.base.BaseActivity;
import com.renwei.yunlong.bean.CommonBean;
import com.renwei.yunlong.bean.ImageUploadBean;
import com.renwei.yunlong.event.ReceiveLocationEvent;
import com.renwei.yunlong.event.SendLocationEvent;
import com.renwei.yunlong.event.WorkPageRefreshEvent;
import com.renwei.yunlong.http.HttpTaskListener;
import com.renwei.yunlong.utils.DateTimeUtils;
import com.renwei.yunlong.utils.JsonMapUtil;
import com.renwei.yunlong.utils.ServiceRequestManager;
import com.renwei.yunlong.utils.StringUtils;
import com.renwei.yunlong.utils.UploadManger;
import com.renwei.yunlong.view.SignatureView;
import com.renwei.yunlong.view.SimpleOptionView;
import com.renwei.yunlong.utils.CommonUtils;
import com.zyf.fwms.commonlibrary.utils.StatusBarUtil;

import java.io.File;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import java.util.HashMap;

import butterknife.Bind;
import butterknife.ButterKnife;
import cn.finalteam.toolsfinal.BitmapUtils;
import de.greenrobot.event.EventBus;
import de.greenrobot.event.Subscribe;
import de.greenrobot.event.ThreadMode;


/**
 * 处理工单完成  签名绘制  页面
 * <p>
 * Created by Administrator on 2017/10/13.
 */

public class WorkHandleDesignActivity extends BaseActivity implements View.OnClickListener, HttpTaskListener {


    @Bind(R.id.simpleTileView)
    SimpleOptionView simpleTileView;
    @Bind(R.id.signa_view)
    SignatureView signaView;
    @Bind(R.id.tv_name)
    TextView tvName;
    @Bind(R.id.tv_date)
    TextView tvDate;
    @Bind(R.id.tv_address)
    TextView tvAddress;
    @Bind(R.id.ll_signa)
    LinearLayout llSigna;
    @Bind(R.id.rl_skip)
    RelativeLayout rlSkip;
    @Bind(R.id.rl_clear)
    RelativeLayout rlClear;
    @Bind(R.id.rl_confirm)
    RelativeLayout rlConfirm;
    @Bind(R.id.ll_go_address)
    LinearLayout llGoAddress;

    private Uri imageUri;
    private HashMap<String, String> map; //处理工单的json

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handle);
        ButterKnife.bind(this);
        EventBus.getDefault().register(this);

        StatusBarUtil.setColor(this, CommonUtils.getColor(this, R.color.title_color), 0);
        map = (HashMap<String, String>) getIntent().getSerializableExtra("map");

        EventBus.getDefault().post(new SendLocationEvent());
        initView();
    }

    private void initView() {
        simpleTileView.setTitle("客户确认签字");

        tvName.setText("1".equals(companyType) ? ownerBean.getRows().getName() : serviceLoginBean.getRows().getName());
        tvDate.setText(DateTimeUtils.date2String(new Date(), "yyyy/MM/dd HH:mm EEEE"));
        llGoAddress.setOnClickListener(this);
        rlSkip.setOnClickListener(this);
        rlClear.setOnClickListener(this);
        rlConfirm.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_confirm: // 上传
                if (!TextUtils.isEmpty(tvAddress.getText().toString())) {
                    getSignaView();
                } else {
                    showCenterInfoMsg("请保证定位权限是否打开");
                }
                break;
            case R.id.rl_clear: // 重新
                signaView.clear();
                break;
            case R.id.rl_skip: //跳过
                finish();
                break;
            case R.id.ll_go_address:
                SignConfirmActivity.OpenActivity(this);
                break;
            default:
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode != 0 && data != null) {
            switch (requestCode) {
                case 999:
                    String address = data.getStringExtra("address");
                    tvAddress.setText(StringUtils.value(address));
                    break;
                default:
                    break;

            }
        }
    }

    private void getSignaView() {
        File file = new File(getApplication().getCacheDir(), "/temp/" + System.currentTimeMillis() + ".jpg");
        if (!file.getParentFile().exists()) {
            file.getParentFile().mkdirs();
        }
        llSigna.setDrawingCacheEnabled(true);
        llSigna.buildDrawingCache();  //启用DrawingCache并创建位图
        Bitmap bitmap = Bitmap.createBitmap(llSigna.getDrawingCache()); //创建一个DrawingCache的拷贝，因为DrawingCache得到的位图在禁用后会被回收
        llSigna.setDrawingCacheEnabled(false);
        BitmapUtils.saveBitmap(bitmap, file);
        imageUri = Uri.fromFile(file);

        File newFile = null;
        try {
            newFile = new File(new URI(String.valueOf(imageUri + "")));
            if (newFile.exists()) {
                UploadManger manger = UploadManger.getManager();
                if ("1".equals(companyType)) {
                    manger.uploadIcon(mContext, newFile, this, ownerBean.getRows().getCompany().getVersionCode()
                            , ownerBean.getRows().getCompany().getCompanyCode());
                } else if ("2".equals(companyType)) {
                    manger.uploadIcon(mContext, newFile, this, serviceLoginBean.getRows().getCompany().getVersionCode()
                            , serviceLoginBean.getRows().getCompany().getCompanyCode());
                }
            }
        } catch (URISyntaxException e) {
            e.printStackTrace();
            showCenterInfoMsg(this.getString(R.string.tip_file_is_not_exist));
        }
    }

    private void uploadSigna(ImageUploadBean bean) {
        map.put("annex", bean.getPath());
        ServiceRequestManager.getManager().setWorkHandler(this, JsonMapUtil.mapToJson(map), this);
    }

    @Override
    public void onSuccess(int requestId, String result) {
        switch (requestId) {
            case 2:
                CommonBean commonBean = new Gson().fromJson(result, CommonBean.class);
                if (commonBean.getMessage().getCode() == 200) {
                    showCenterSuccessMsg("操作成功");
                    EventBus.getDefault().post(new WorkPageRefreshEvent(true));
                    finish();
                } else {
                    showCenterInfoMsg(commonBean.getMessage().getMessage());
                }
                break;
            case 999: //上传
                ImageUploadBean bean = new Gson().fromJson(result, ImageUploadBean.class);
                if ("1".equals(bean.getStatus())) {  //成功
                    uploadSigna(bean);
                } else {
                    //失败
                    showCenterInfoMsg("上传失败！");
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void onException(int requestId, String code) {
        showTopWrongMsg(getResources().getString(R.string.net_work_error));
    }

    @Subscribe(threadMode = ThreadMode.MainThread)
    public void onReceiveLocationEvent(ReceiveLocationEvent event) {
        BDLocation location = event.location;
        if (location != null) {
            tvAddress.setText(StringUtils.value(location.getAddress().address+location.getPoiList().get(0).getName()));
        } else {
            EventBus.getDefault().post(new SendLocationEvent());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static void OpenActivity(Context context, HashMap<String, String> map) {
        Intent intent = new Intent(context, WorkHandleDesignActivity.class);
        intent.putExtra("map", map);
        context.startActivity(intent);
    }
}
